<template>
  <div class="department-management">
    <div class="page-header">
      <h2>院系管理</h2>
      <div class="page-info">
        <el-tag size="small" type="info">数据统计</el-tag>
        <span class="stat-item"><i class="el-icon-data-line"></i> 院系总数：{{ filteredData.length }}</span>
      </div>
    </div>
    
    <el-card class="box-card" shadow="hover">
      <div class="toolbar">
        <el-button type="primary" icon="el-icon-plus" @click="openAddDialog">新增院系</el-button>
        <div class="search-form">
          <el-input
            placeholder="搜索院系名称"
            v-model="searchQuery"
            style="width: 200px; margin-right: 10px;"
            clearable
            @clear="handleSearch"
            @keyup.enter.native="handleSearch"
            size="small"
          >
            <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
          </el-input>
        </div>
      </div>
      
      <el-table 
        :data="paginatedData" 
        style="width: 100%;" 
        border 
        stripe 
        highlight-current-row
        v-loading="loading"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        class="department-table"
      >
        <el-table-column prop="id" label="ID" width="60" align="center" />
        <el-table-column label="院系Logo" width="100" align="center">
          <template slot-scope="scope">
            <el-image 
              v-if="scope.row.logoUrl" 
              :src="scope.row.logoUrl" 
              style="width: 40px; height: 40px;" 
              fit="contain"
              :preview-src-list="[scope.row.logoUrl]"
            />
            <i v-else class="el-icon-picture-outline" style="font-size: 24px; color: #ccc;"></i>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="院系名称" width="150" show-overflow-tooltip />
        <el-table-column prop="intro" label="院系介绍" min-width="150" show-overflow-tooltip />
        <el-table-column label="宣传视频" width="120" align="center">
          <template slot-scope="scope">
            <el-button v-if="scope.row.videoUrl" size="mini" type="text" @click="previewVideo(scope.row)">
              <i class="el-icon-video-camera"></i> 预览
            </el-button>
            <span v-else class="no-data-text">无视频</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="openEditDialog(scope.row)">
              <i class="el-icon-edit"></i> 编辑
            </el-button>
            <el-button size="mini" type="text" style="color: #F56C6C" @click="handleDelete(scope.row.id)">
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 无数据提示 -->
      <div v-if="!loading && paginatedData.length === 0" class="empty-container">
        <el-empty description="暂无院系数据">
          <el-button type="primary" size="small" @click="openAddDialog">添加院系</el-button>
        </el-empty>
      </div>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredData.length"
          background
        >
        </el-pagination>
      </div>
      
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" status-icon>
        <el-form-item label="院系名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入院系名称" />
        </el-form-item>
        <el-form-item label="院系介绍" prop="intro">
          <el-input type="textarea" v-model="form.intro" :rows="4" placeholder="请输入院系介绍" />
        </el-form-item>
        <el-form-item label="院系Logo" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/admin/upload/image"
            :show-file-list="false"
            :on-success="handleLogoSuccess"
            :before-upload="beforeLogoUpload"
          >
            <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="upload-tip">建议上传正方形图片，大小不超过2MB</div>
        </el-form-item>
        <el-form-item label="宣传视频" prop="videoUrl">
          <el-upload
            class="video-uploader"
            action="/admin/upload/video"
            :show-file-list="false"
            :on-success="handleVideoSuccess"
            :before-upload="beforeVideoUpload"
          >
            <div v-if="form.videoUrl" class="video-preview">
              <i class="el-icon-video-camera"></i>
              <span>已上传视频</span>
            </div>
            <i v-else class="el-icon-plus video-uploader-icon"></i>
          </el-upload>
          <div v-if="form.videoUrl" class="video-actions">
            <el-button size="mini" type="text" @click="previewVideo(form)">
              <i class="el-icon-video-play"></i> 预览
            </el-button>
            <el-button size="mini" type="text" @click="clearVideo">
              <i class="el-icon-delete"></i> 清除
            </el-button>
          </div>
          <div class="upload-tip">支持mp4、avi等常见视频格式，大小不超过50MB</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 视频预览弹窗 -->
    <el-dialog title="视频预览" :visible.sync="videoDialogVisible" width="60%" center>
      <div class="video-player-container">
        <video v-if="currentVideoUrl" :src="currentVideoUrl" controls class="video-player" ref="videoPlayer"></video>
        <div v-else class="no-video">无可预览的视频</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'DepartmentManagement',
  data() {
    return {
      departmentList: [],
      dialogVisible: false,
      dialogTitle: '新增院系',
      form: {
        id: null,
        name: '',
        intro: '',
        logoUrl: '',
        videoUrl: ''
      },
      rules: {
        name: [{ required: true, message: '请输入院系名称', trigger: 'blur' }],
      },
      isEdit: false,
      videoDialogVisible: false,
      currentVideoUrl: '',
      loading: false,
      
      // 分页相关
      currentPage: 1,
      pageSize: 10,
      
      // 搜索相关
      searchQuery: ''
    };
  },
  computed: {
    filteredData() {
      if (!this.searchQuery) {
        return this.departmentList;
      }
      return this.departmentList.filter(item => 
        item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      );
    },
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredData.slice(start, end);
    }
  },
  mounted() {
    this.fetchDepartments();
  },
  methods: {
    fetchDepartments() {
      this.loading = true;
      axios.get('/admin/department/list').then(res => {
        this.loading = false;
        if (res.data.code === 200) {
          this.departmentList = res.data.data || [];
        } else {
          this.$message.error(res.data.message || '获取院系列表失败');
        }
      }).catch(err => {
        this.loading = false;
        console.error('获取院系列表出错:', err);
        this.$message.error('获取院系列表失败');
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1; // 重置为第一页
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    handleSearch() {
      this.currentPage = 1; // 搜索时重置为第一页
    },
    openAddDialog() {
      this.dialogTitle = '新增院系';
      this.isEdit = false;
      this.form = { id: null, name: '', intro: '', logoUrl: '', videoUrl: '' };
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef && this.$refs.formRef.clearValidate();
      });
    },
    openEditDialog(row) {
      this.dialogTitle = '编辑院系';
      this.isEdit = true;
      this.form = { ...row };
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef && this.$refs.formRef.clearValidate();
      });
    },
    handleSubmit() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return;
        
        const loading = this.$loading({
          lock: true,
          text: this.isEdit ? '正在保存...' : '正在创建...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        
        if (this.isEdit) {
          axios.post('/admin/department/update', this.form).then(res => {
            loading.close();
            if (res.data.code === 200) {
              this.$message.success('修改成功');
              this.dialogVisible = false;
              this.fetchDepartments();
            } else {
              this.$message.error(res.data.message || '修改失败');
            }
          }).catch(err => {
            loading.close();
            console.error('修改院系出错:', err);
            this.$message.error('修改失败');
          });
        } else {
          axios.post('/admin/department/add', this.form).then(res => {
            loading.close();
            if (res.data.code === 200) {
              this.$message.success('新增成功');
              this.dialogVisible = false;
              this.fetchDepartments();
            } else {
              this.$message.error(res.data.message || '新增失败');
            }
          }).catch(err => {
            loading.close();
            console.error('新增院系出错:', err);
            this.$message.error('新增失败');
          });
        }
      });
    },
    handleDelete(id) {
      this.$confirm('确定要删除该院系吗？删除后不可恢复！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在删除...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        
        axios.delete(`/admin/department/delete/${id}`).then(res => {
          loading.close();
          if (res.data.code === 200) {
            this.$message.success('删除成功');
            this.fetchDepartments();
          } else {
            this.$message.error(res.data.message || '删除失败');
          }
        }).catch(err => {
          loading.close();
          console.error('删除院系出错:', err);
          this.$message.error('删除失败');
        });
      }).catch(() => {
        // 取消删除
      });
    },
    beforeLogoUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('只能上传图片文件');
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },
    handleLogoSuccess(res) {
      if (res.code === 200) {
        this.form.logoUrl = res.data;
      } else {
        this.$message.error(res.message || '上传失败');
      }
    },
    beforeVideoUpload(file) {
      const isVideo = file.type.startsWith('video/');
      const isLt50M = file.size / 1024 / 1024 < 50;

      if (!isVideo) {
        this.$message.error('只能上传视频文件');
      }
      if (!isLt50M) {
        this.$message.error('视频大小不能超过 50MB!');
      }
      return isVideo && isLt50M;
    },
    handleVideoSuccess(res) {
      if (res.code === 200) {
        this.form.videoUrl = res.data;
      } else {
        this.$message.error(res.message || '上传失败');
      }
    },
    previewVideo(row) {
      if (row.videoUrl) {
        this.currentVideoUrl = row.videoUrl;
        this.videoDialogVisible = true;
        // 在下一个事件循环中，确保DOM已更新后再播放视频
        this.$nextTick(() => {
          if (this.$refs.videoPlayer) {
            this.$refs.videoPlayer.play();
          }
        });
      } else {
        this.$message.warning('没有可预览的视频');
      }
    },
    clearVideo() {
      this.form.videoUrl = '';
    }
  }
};
</script>

<style scoped>
.department-management {
  padding: 20px;
  min-height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.page-info {
  display: flex;
  align-items: center;
}

.stat-item {
  margin-left: 15px;
  font-size: 13px;
  color: #606266;
}

.box-card {
  flex: 1;
  margin-bottom: 20px;
  box-shadow: 0 4px 18px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.toolbar {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
}

.toolbar > .el-button {
  margin-right: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.avatar-uploader, .video-uploader {
  display: inline-block;
}

.avatar-uploader-icon, .video-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
}

.avatar-uploader-icon:hover, .video-uploader-icon:hover {
  border-color: #409EFF;
  color: #409EFF;
}

.avatar {
  width: 40px;
  height: 40px;
  display: block;
  border-radius: 4px;
}

.video-preview {
  width: 120px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.video-preview i {
  margin-right: 5px;
  color: #409EFF;
}

.video-actions {
  margin-top: 8px;
}

.video-player-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.video-player {
  width: 100%;
  max-height: 500px;
  border-radius: 4px;
}

.no-video {
  color: #909399;
  font-size: 16px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.no-data-text {
  color: #909399;
  font-size: 13px;
}

.empty-container {
  margin: 40px 0;
  text-align: center;
}

/* 提示区域 */
.tips-container {
  margin-top: 20px;
  padding: 15px;
  display: flex;
  background-color: #f4f6fa;
  border-radius: 4px;
}

.tip-icon {
  font-size: 24px;
  color: #e6a23c;
  margin-right: 15px;
}

.tip-content {
  flex: 1;
}

.tip-title {
  font-weight: bold;
  margin-bottom: 5px;
  color: #606266;
}

.tip-text {
  color: #606266;
  font-size: 13px;
}

.tip-text p {
  margin: 5px 0;
}

/* 表头居中 */
::v-deep .el-table th {
  text-align: center !important;
  background-color: #f5f7fa;
}

/* 单元格居中 */
::v-deep .el-table .cell {
  text-align: center;
}

::v-deep .el-table__header-wrapper .el-table__header th {
  padding: 12px 0;
}
</style> 